<template>
	<view>
		<cu-page-bg></cu-page-bg>
		<view class="cu-w-100">
			<cu-navbar :title="isRegister ? '注册' : '个人信息'" :placeholder="true" @leftClick="vk.navigateBack()"
				:showLeft="true" :leftIconColor="{color:backgroundStyle.color}"
				:titleStyle="{color:backgroundStyle.color}" :style="getBackgroundStyle"
				bgColor="rgb(255,255,255,0)"></cu-navbar>
			<view class="cu-w-100 cu-p-20 cu-pt-50 cu-border-box">
				<u--form :model="modelInp" ref="uForm">
					<u-form-item prop="userInfo.name" borderBottom ref="item1">
						<view class="cu-w-100 cu-row cu-flex-row cu-j-center cu-a-center cu-border-box">
							<button size="mini" style="border: 0;" class="avatar-button" plain open-type="chooseAvatar"
								@chooseavatar="onChooseAvatar">
								<u-avatar :src="modelInp.userInfo.avatar" size="80"></u-avatar>
							</button>
							<view class="cu-w-100 cu-mt-20">
								<u--input placeholder="请输入昵称" type="nickname" border="surround"
									v-model="modelInp.userInfo.nickname" clearable></u--input>
							</view>
							<view class="cu-w-100 cu-mt-20">
								<u--input placeholder="请输入座右铭" type="motto" border="surround"
									v-model="modelInp.userInfo.motto" clearable></u--input>
							</view>
						</view>
					</u-form-item>
				</u--form>
				<u-button :color="buttonColor" @click="submit">提交</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		computed: {
			getBackgroundStyle() {
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			},
			isRegister() {
				const nickname = vk.getVuex("$user.userInfo.nickname") || '';
				if (nickname === '') {
					return true;
				}
				return false;
			}
		},
		data() {
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				buttonColor: "linear-gradient(to right, " + vk.getVuex('$app.color.main') + "," + vk.getVuex(
					'$app.color.secondary') + ")",
				backgroundStyle: {
					color: "#FFF"
				},
				modelInp: {
					userInfo: {
						nickname: vk.getVuex("$user.userInfo.nickname") || '',
						avatar: vk.getVuex("$user.userInfo.avatar") || '',
						motto: vk.getVuex("$user.userInfo.motto") || '',
					},
				},
				rules: {
					'userInfo.nickname': {
						type: 'string',
						required: true,
						message: '请填写昵称',
						trigger: ['blur', 'change']
					},
					'userInfo.motto': {
						type: 'string',
						required: false,
						max: 30,
						message: '座右铭超长',
						trigger: ['blur', 'change']
					}
				},
			};
		},
		onLoad(options) {
			vk = uni.vk;
			this.init(options);
			// 校验是已经授权
			this.getWxSetting();
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onShow() {
			this.init(undefined);
		},
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
			},
			getWxSetting() {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.userInfo']) {
							// 未授权,发起授权
							wx.authorize({
								scope: 'scope.userInfo',
								success() {
									// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
									wx.startRecord()
								}
							})
						}
					}
				});
			},
			onChooseAvatar(e) {
				const avatarUrl = e.detail.avatarUrl
				this.modelInp.userInfo.avatar = avatarUrl;
			},
			async submit() {
				// 执行注册
				if (this.isRegister) {
					this.resisterFun();
				}
				// 执行修改
				else {
					await this.updateFun()
					// 跳转到登录页面
					vk.reLaunch("/pages/index/index")
				}
			},
			resisterFun() {
				let that = this
				this.$refs.uForm.validate().then(async res => {
					// 上传图片到云储存
					let dataJson = {};
					if (this.modelInp.userInfo.avatar.indexOf("https://") !== 0) {
						let uploadFileRes = await vk.uploadFile({
							filePath: this.modelInp.userInfo.avatar,
							fileType: "image"
						});
						dataJson.avatar = uploadFileRes.url;
						dataJson.avatarFileID = uploadFileRes.fileID
					} else {
						dataJson.avatar = this.modelInp.userInfo.avatar;
					}
					dataJson.nickname = this.modelInp.userInfo.nickname;
					dataJson.type = "register";
					dataJson.motto = this.modelInp.userInfo.motto;
					await vk.userCenter.loginByWeixin({
						data: dataJson,
						success: (data) => {
							console.log("success ", data)
							if (data && data.code !== 0) {
								vk.alert(data.msg);
								return
							}
							that.data = data;
							vk.reLaunch("/pages/index/index");
						},
						fail: (data) => {
							console.log('fail', data)
							vk.alert("注册失败");
						}
					});
				
				
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			async updateFun() {
				let that = this
				await this.$refs.uForm.validate().then(async res => {
					
					// 上传图片到云储存
					let dataJson = {};
					
					// 更新头像
					if(this.modelInp.userInfo.avatar !== vk.getVuex("$user.userInfo.avatar")){
						// console.log("更新头像")
						if (this.modelInp.userInfo.avatar.indexOf("https://") !== 0) {
							let uploadFileRes = await vk.uploadFile({
								filePath: this.modelInp.userInfo.avatar,
								fileType: "image"
							});
							dataJson.avatar = uploadFileRes.url;
							dataJson.avatarFileID = uploadFileRes.fileID
						} else {
							dataJson.avatar = this.modelInp.userInfo.avatar;
						}
						
						let userInfo = vk.getVuex("$user.userInfo");
						
						/**
						 * 设置头像
						 * data 请求参数 说明
						 * @param {String} avatar 头像地址
						 * @param {Boolean} deleteOldFile 是否同时删除云储存内的旧头像文件
						 */
						await vk.userCenter.setAvatar({
						  data: {
						    avatar: dataJson.avatar,
							userInfo: userInfo,
						    deleteOldFile: true, // 是否同时删除云储存内的旧头像文件，true代表是
						  },
						  success: (data) => {
							// 设置缓存
							vk.setVuex('$user.userInfo.avatar', dataJson.avatar);
							vk.setVuex('$user.userInfo.avatarFileID', dataJson.avatarFileID);
						  },
						  fail: (data) => {
						  	// console.log('fail', data)
						  	vk.alert("服务器繁忙");
						  }
						});
						
					}
					
					// 更新昵称
					let mark = this.modelInp.userInfo.nickname !== vk.getVuex("$user.userInfo.nickname") || this.modelInp.userInfo.motto !== vk.getVuex("$user.userInfo.motto")
					if (mark) {
						// console.log("更新昵称")
						dataJson.nickname = this.modelInp.userInfo.nickname;
						dataJson.motto = this.modelInp.userInfo.motto;
						/**
						 * 设置昵称等用户展示的个人信息
						 * data 请求参数 说明
						 * @param {String} nickname 昵称
						 * @param {String} avatar 头像
						 * @param {Number} gender 性别
						 */
						await vk.userCenter.updateUser({
						  data: dataJson,
						  success: (data) => {
							// 设置缓存
							vk.setVuex('$user.userInfo.nickname', dataJson.nickname);
							vk.setVuex('$user.userInfo.motto', dataJson.motto);
						  },
						  fail: (data) => {
						  	console.log('fail', data)
						  	vk.alert("服务器繁忙");
						  }
						});
					}
					
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			}

		}
	};
</script>

<style lang="scss" scoped>

</style>